//
//  AppDelegate.m
//  ZPSALE
//
//  Created by fei on 14-8-12.
//  Copyright (c) 2014年 self. All rights reserved.
//

#import "AppDelegate.h"
#import "MobClick.h"
#import "IntroductionView.h"
#define ZhenPinSale_UMKey @"53fc2fd7fd98c561c500ae87"
@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    //友盟分析统计
    [MobClick startWithAppkey:ZhenPinSale_UMKey reportPolicy:BATCH channelId:nil];
    [CheckLoginObject shareCheckLogin];
    NSUserDefaults *userD = [NSUserDefaults standardUserDefaults];
    if (![[userD objectForKey:@"isFirst"] boolValue]) {
        [self setLeadPage];
        [self clearUserInfo];
    }
//    登录验证
    [self registerAndSign];
    [self setOnlineServiceAddress];
    
    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    
    return YES;
}

-(void)setLeadPage {
    
    UITabBarController *tabBarVC = (UITabBarController *)[self.window rootViewController];
    CGRect rect = [[UIScreen mainScreen] bounds];
    NSString *imageNameHeader;
    if (iPhone5) {
        imageNameHeader = @"lead_phone5_0";
    } else {
        imageNameHeader = @"lead_phone4_0";
    }
    int num = 4;
    NSMutableArray *mPaneViewArray = [[NSMutableArray alloc] initWithCapacity:0];
    for ( int i = 0; i < num; i ++) {
        PanelView *customView = [[PanelView alloc] initWithFrame:rect andBackGroundImage:[NSString stringWithFormat:@"%@%d",imageNameHeader,i + 1]];
        if (i==num-1) {
            [customView addClickedButtonWithFrame:CGRectMake(96.5, rect.size.height-58, 127, 32) andNormalImage:@"loading_icon" andHelightImage:@"loading_icon_down"];
        }
        [mPaneViewArray addObject:customView];
    }
    IntroductionView *mIntroduceView = [[IntroductionView alloc] initWithFrame:rect andIntroductionViewsArray:mPaneViewArray];
    mIntroduceView.backgroundColor = [UIColor whiteColor];
    [tabBarVC.view addSubview:mIntroduceView];
}


- (void)registerAndSign
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/UserInfo.plist"];
    if (![fileManager fileExistsAtPath:homePath]) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"UserInfo" ofType:@"plist"];
        [fileManager copyItemAtPath:path toPath:homePath error:nil];
    }
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    NSString *string = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    [dataDic setValue:string forKey:@"aliasid"];
    NSString *memberId = dataDic[@"memberId"];
    if ([memberId length]==0 || [memberId isEqual:[NSNull null]]) {
        
    } else {
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        NSDictionary *params = @{@"username": dataDic[@"userName"],
                                 @"password": dataDic[@"passwd"],
                                 @"isuname": @"1",
                                 @"apptype": @"1"
                                 };
        
        [manager POST:APIURL@"ucmembers/onLogin.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSDictionary *_logResult = (NSDictionary *)responseObject;
            if ([_logResult valueForKey:@"result"]) {
                [dataDic setValue:[NSString stringWithFormat:@"%@",_logResult[@"username"]] forKey:@"userName"];
                [dataDic setValue:[NSString stringWithFormat:@"%@",_logResult[@"memberid"]] forKey:@"memberId"];
                [dataDic setValue:[NSString stringWithFormat:@"%@",_logResult[@"token"]] forKey:@"token"];
                [dataDic writeToFile:homePath atomically:YES];
                [CheckLoginObject saveLoginWithStatus:YES];
            }else{
                [CheckLoginObject saveLoginWithStatus:NO];
                if ([_logResult valueForKey:@"error"]) {
                    
                }
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            [CheckLoginObject saveLoginWithStatus:NO];
        }];
        
    }
    [dataDic writeToFile:homePath atomically:YES];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeNumberOfProductInCart" object:nil];
}

-(void)clearUserInfo {
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:homePath]) {
        NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
        [dataDic setValue:@"" forKey:@"userName"];
        [dataDic setValue:@"" forKey:@"passwd"];
        [dataDic setValue:@"" forKey:@"memberId"];
        [dataDic setValue:@"" forKey:@"token"];
        [dataDic writeToFile:homePath atomically:YES];
    }
}

-(void)setOnlineServiceAddress {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/ServerConfig.plist"];
    if (![fileManager fileExistsAtPath:homePath]) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"ServerConfig" ofType:@"plist"];
        //        [fileManager createFileAtPath:homePath contents:nil attributes:nil];
        [fileManager copyItemAtPath:path toPath:homePath error:nil];
    }
    NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
    
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    [httpManager GET:APIURL"homePage/serverConfig.json" parameters:nil success:^(AFHTTPRequestOperation *operation,id resultObject) {
        
        if (resultObject[@"zpAboutus"]) {
            [dataDic setValue:resultObject[@"zpAboutus"] forKey:@"zpAboutus"];
        }
        if (resultObject[@"zpAgreement"]) {
            [dataDic setValue:resultObject[@"zpAgreement"] forKey:@"zpAgreement"];
        }
        if (resultObject[@"zpGetMyPass"]) {
            [dataDic setValue:resultObject[@"zpGetMyPass"] forKey:@"zpGetMyPass"];
        }
        if (resultObject[@"zpHelp"]) {
            [dataDic setValue:resultObject[@"zpHelp"] forKey:@"zpHelp"];
        }
        //图文详情
        if (resultObject[@"zpProductDraw"]) {
            [dataDic setValue:resultObject[@"zpProductDraw"] forKey:@"zpProductDraw"];
        } else {
            [dataDic setValue:@"http://m.zhenpin.com/index.php?c=APP_product&a=productdraw&pid=" forKey:@"zpProductDraw"];
        }
        
        //尺码详情
        if (resultObject[@"zpProductSize"]) {
            [dataDic setValue:resultObject[@"zpProductSize"] forKey:@"zpProductSize"];
        } else {
            [dataDic setValue:@"http://m.zhenpin.com/index.php?c=APP_product&a=productsize&pid=" forKey:@"zpProductSize"];
        }
        
        if (resultObject[@"zpSever"]) {
            [dataDic setValue:resultObject[@"zpSever"] forKey:@"zpSever"];
        } else {
            [dataDic setValue:@"http://m.zhenpin.com/special/serve.html" forKey:@"zpSever"];
        }
        if (resultObject[@"zpSpecialList"]) {
            [dataDic setValue:resultObject[@"zpSpecialList"] forKey:@"zpSpecialList"];
        }
        
        
        [dataDic writeToFile:homePath atomically:YES];
    }failure:^(AFHTTPRequestOperation *operation,NSError *error){
    }];
    
}

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    if (deviceToken) {
        NSMutableString *tokenString = [NSMutableString stringWithFormat:@"%@",deviceToken];
        NSString *string = [tokenString substringWithRange:NSMakeRange(1, tokenString.length-2)];
        
        NSString *tokenFinal = [string stringByReplacingOccurrencesOfString:@" " withString:@""];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"/Documents/UserInfo.plist"];
        if (![fileManager fileExistsAtPath:homePath]) {
            NSString *path = [[NSBundle mainBundle] pathForResource:@"UserInfo" ofType:@"plist"];
            [fileManager copyItemAtPath:path toPath:homePath error:nil];
        }
        NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
        [dataDic setObject:tokenFinal forKey:@"devicetoken"];
        [dataDic writeToFile:homePath atomically:YES];
        
        NSDictionary *dict = @{@"model": tokenFinal,
                               @"apptype":@"1",
                               };
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager POST:APIURL"ucmembers/initModel.json" parameters:dict success:^(AFHTTPRequestOperation *operation ,id resultObject){
            
            
            
        }failure:^(AFHTTPRequestOperation *operation,NSError *error){
      
        }];
    }
}

-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error{
    
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [CheckLoginObject shareCheckLogin];
    [[NSNotificationCenter defaultCenter] postNotificationName:StringForCheckLogin object:nil];
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end
